using DevExpress.Data.Filtering;
using DevExpress.Xpo;
using SmartPeople.Framework.Security.Providers.XPO;
using SmartPeople.Framework.SecuritySpace;

namespace SmartPeople.Framework.Security.Providers.XPO
{
    internal class XPSecuritySecuredTypeStates : ISecuritySecuredTypeStates
    {
        private XPSecuritySecuredType securedType;

        public XPSecuritySecuredTypeStates(XPSecuritySecuredType securedDocument)
        {
            securedType = securedDocument;
        }


        int ISecuritySecuredTypeStates.Count
        {
            get
            {
                int resultCount = securedType.states.Count;
                if (securedType.BaseSecuredType != null)
                    resultCount += securedType.BaseSecuredType.States.Count;
                return resultCount;
            }
        }


        public ISecuritySecuredTypeState this[string stateName]
        {
            get
            {
                CriteriaOperator criteria = new BinaryOperator("Name", stateName, BinaryOperatorType.Equal);
                XPCollection<XPSecuritySecuredTypeState> actions = new
                    XPCollection<XPSecuritySecuredTypeState>(securedType.states, criteria);
                if (actions.Count == 1)
                {
                    return actions[0];
                }

                if (securedType.BaseSecuredType != null)
                {
                    return securedType.BaseSecuredType.States[stateName];
                }


                return null;
            }
        }

        #region CreateState

        public ISecuritySecuredTypeState CreateState(string stateName)
        {
            XPSecuritySecuredTypeState securedTypeState = new XPSecuritySecuredTypeState(securedType.Session);
            securedTypeState.Name = stateName;
            securedTypeState.securedDocument = securedType;
            securedType.states.Add(securedTypeState);
            return securedTypeState;
        }

        #endregion
    }
}